/*! Sick Code | http://calvindavis.co.uk/sick/code/ */
;(function($, window) {
		   
	var methods = {
		
		_init: function(options) {
			var settings = $.extend({}, $.code.defaults, options),
				code = methods._getCode(settings.code),
				length = code.length,
				timeout = !isNaN(settings.timeout) ? settings.timeout : $.code.defaults.timeout,
				callback = typeof settings.callback == 'function' ? settings.callback : $.code.defaults.callback,
				input = [],
				timeoutID = null;
				
			$(window).on('keypress.code', function(e) {
				console.log(e);
				
				// Push keycode into input
				input.push(e.which);
				
				// Trim input to length of code
				while (input.length > length) {
					input.shift();
				}
				
				// Compare input to code
				if (methods._compareArrays(input, code)) {
					console.log('GO');
					callback();
				}
				
				// Restart timeout
				clearTimeout(timeoutID);
				timeoutID = setTimeout(function () { input = []; }, timeout);
				
				console.log(input);
				console.log(code);
			});
		},
		
		_destroy: function(options) {
			$(window).off('keypress.code');
		},
		
		_getCode: function(rawCode) {			
			switch(typeof rawCode) {
				case 'string':
					rawCode = rawCode.split('');
				case 'object':
					var code = [];
					for (var n = 0; n < rawCode.length; ++n) {
						charCode = isNaN(rawCode[n]) ? rawCode[n].charCodeAt(0) : rawCode[n];
						code.push(charCode);
					}
					return code;
					break;
			}
			
			return $.code.defaults.code;
		},
		
		_compareArrays: function(a, b) {			
			if (!($.isArray(a) && $.isArray(b))) {
				return false;
			}
			
			if (a.length !== b.length) {
				return false;
			}
			
			for (var n = 0; n < a.length; n++) {
				if (a[n] !== b[n]) {
					return false;
				}
			}
			
			return true;
		}
	};
	
	$.code = function(options) {
		if (typeof methods[options] == 'function') {
			methods[options]();
		} else if (typeof options == 'object') {
			methods._init.apply(this, [options]);
		} else {
			method._init();
		}
	};
	
	// Defaults
	$.code.defaults = {
		code: [115, 105, 99, 107, 99, 111, 100, 101],
		timeout: 250,
		callback: function() {}
	};
	
})(jQuery, window);